﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Web.DbHelper;
using System.IO;

namespace KnowledgeCommunity.Web.Controllers
{
    public class TribuneController : Controller
    {
        TribuneHelper myTribuneHelper = new TribuneHelper();
        TribuneTopicHelper myTribuneTopicHelper = new TribuneTopicHelper();
        //
        // GET: /Tribune/

        public ActionResult Index()
        {
            var Tribune = myTribuneHelper.FindAll();
            ViewData["TribuneList"] = Tribune;
            return View();
        }

        [Authorize(Roles="admin,editor")]
        public ActionResult List()
        {
            KnowledgeCommunity.Web.Models.Page Model = new Page();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Tribune> datesource = GetDataSource();//要分页的数据源
            Model.TribuneList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.TribuneList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Tribune> GetDataSource()
        {
            var Tribune = myTribuneHelper.FindAll();
            List<Tribune> model = new List<Tribune>();
            foreach (var item in Tribune)
            {
                model.Add(item);
            }
            return model;
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult PageIndex(Models.Page Model)
        {

            //分页数据源。自己写逻辑获取。

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Tribune> datesource = GetDataSource();//要分页的数据源
            Model.TribuneList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("List", Model);
            }
            //return View(Model);
        }

        public ActionResult Details(int id)
        {
            var model = myTribuneHelper.FindById(id);
            ViewData["appList"] = myTribuneTopicHelper.FindByShapeCode(model.ShapeCode);
            return View(model);
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult TopicCreate(TribuneTopic model)
        {
            string Id = Request.Form["Id"];

            string code = Request.Form["ShapeCode"];
            if ((Id != "" && code != "") || (Id != null && code != null))
            {
                model.Content = Request.Form["message"];
                model.AddTime = DateTime.Now;
                model.UserName = HttpContext.User.Identity.Name;
                model.ShapeCode = code;
                bool n = myTribuneTopicHelper.Create(model);
                if (n)
                {
                    int _id = Convert.ToInt32(Id);
                    var t1 = myTribuneHelper.FindById(_id);
                    t1.TopicNumber++;
                    DoUpdateModel(t1);
                    return RedirectToAction("Details", "Tribune", new { id = Id });
                }
                else
                {
                    return RedirectToAction("Error", "Notice", new { type = 1 });
                }
            }
            else
            {
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Create(Tribune model)
        {
            
            string fileOldName = null;
            string extension = null;
            string path = null;
            string url = null;

            foreach (string image in Request.Files)
            {
                if (!HasFiles.HasFile(Request.Files[image]))
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"UpLoad\Tributes";
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[image].FileName);
                extension = Path.GetExtension(fileOldName);//扩展名 ".xxx"

                string miniType = Request.Files[image].ContentType.ToLower();

                Stream fileStream = Request.Files[image].InputStream;

                //文件重命名
                string fileNewName = RandomNumber.RandomNumberToName() + extension;

                Request.Files[image].SaveAs(Path.Combine(path, fileNewName));

                path = path + "\\" + fileNewName;
                url = "~\\UpLoad\\Tributes\\" + fileNewName;

            }
            if (url != null && path != null)
            {
                model.Logo = url;
                model.DelPath = path;
            }
            model.Sponsor = HttpContext.User.Identity.Name;
            model.AddTime = DateTime.Now;
            //model.Content = Request.Form["Content"];
            model.ShapeCode = "T" + RandomNumber.GenerateRandomNumber();
            model.TopicNumber = 0;
            model.State = 0;

            bool n = myTribuneHelper.Create(model);
            if (n)
            {
                if (HttpContext.User.IsInRole("editor") || HttpContext.User.IsInRole("admin"))
                {
                    return RedirectToAction("List", "Tribune");
                }
                else
                {
                    return RedirectToAction("MyTribune", "Zone");
                }
            }
            else
            {
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            var _Tribune = myTribuneHelper.FindById(id);
            return View(_Tribune);
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Edit(Tribune model)
        {
            DoUpdateModel(model);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            var _Tribune = myTribuneHelper.FindById(id);
            return View(_Tribune);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = myTribuneHelper.Delete(id);
            if (n)
            {
                if (HttpContext.User.IsInRole("editor") || HttpContext.User.IsInRole("admin"))
                {
                    return RedirectToAction("List", "Tribune");
                }
                else
                {
                    return RedirectToAction("MyTribune", "Zone");
                }
            }
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Approve(int id)
        {
            var model = myTribuneHelper.FindById(id);
            model.State = 1;
            DoUpdateModel(model);
            return RedirectToAction("Waiting", "Zone");
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Cancel(int id)
        {
            var model = myTribuneHelper.FindById(id);
            model.State = 2;
            DoUpdateModel(model);
            return RedirectToAction("Waiting", "Zone");
        }

        CKCDB mydb = new CKCDB();
        private void DoUpdateModel(Tribune model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.Tribunes.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Tribunes>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
        }

    }
}
